package org.example.leetcode.addon.lc93;

import java.util.LinkedList;
import java.util.List;

public class Solution {
    List<String> ans = new LinkedList<>();

    public List<String> restoreIpAddresses(String s) {
        if (s.length() > 12) return ans;
        backtracking(s, 0, 0);

        return ans;
    }

    private void backtracking(String str, int startIndex, int pointNum) {
        if (pointNum == 3 && isValid(str, startIndex, str.length() - 1)) {
            ans.add(str);
            return;
        }

        for (int i = startIndex; i < str.length(); i++) {
            if (isValid(str, startIndex, i)) {
                str = str.substring(0, i + 1) + "." + str.substring(i + 1);
                pointNum++;
                backtracking(str, i + 2, pointNum); // i + 2因为在str后面插了个'.'
                pointNum--;
                str = str.substring(0, i + 1) + str.substring(i + 2);
            } else {
                break;
            }
        }
    }

    private boolean isValid(String str, int start, int end) {
        if (start > end) {
            return false;
        }
        if (str.charAt(start) == '0' && start != end) {
            return false;
        }
        int num = 0;
        for (int i = start; i <= end; i++) {
            if (str.charAt(i) > '9' || str.charAt(i) < '0') {
                return false;
            }
            num = num * 10 + (str.charAt(i) - '0');
            if (num > 255) {
                return false;
            }
        }

        return true;
    }
}
